package cn.ewsd.common.controller;

import cn.ewsd.common.license.*;
import cn.ewsd.common.utils.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于生成证书文件，不能放在给客户部署的代码里
 *
 * @author小策一喋
 * @date 2018/4/26
 * @since 1.0.0
 */
@Controller
@RequestMapping("/license")
public class LicenseCreatorController {

    /**
     * 证书生成路径
     */
    @Value("${license.licensePath}")
    private String licensePath;

    @RequestMapping(value = "/index")
    public String index() {
        return "index";
    }

    /**
     * 获取服务器硬件信息
     *
     * @param osName 操作系统类型，如果为空则自动判断
     * @return com.ccx.models.license.LicenseCheckModel
     * @author小策一喋
     * @date 2018/4/26 13:13
     * @since 1.0.0
     */
    @RequestMapping(value = "/getServerInfos", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public LicenseCheckModel getServerInfos(@RequestParam(value = "osName", required = false) String osName) {
        //操作系统类型
        if (StringUtils.isBlank(osName)) {
            osName = System.getProperty("os.name");
        }
        osName = osName.toLowerCase();

        AbstractServerInfos abstractServerInfos = null;

        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        } else {//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }

        return abstractServerInfos.getServerInfos();
    }

    /**
     * 生成证书
     *
     * @param param 生成证书需要的参数，如：{"subject":"ccx-models","privateAlias":"privateKey","keyPass":"5T7Zz5Y0dJFcqTxvzkH5LDGJJSGMzQ","storePass":"3538cef8e7","licensePath":"C:/Users/zhaoxiace/Desktop/license.lic","privateKeysStorePath":"C:/Users/zhaoxiace/Desktop/privateKeys.keystore","issuedTime":"2018-04-26 14:48:12","expiryTime":"2018-12-31 00:00:00","consumerType":"User","consumerAmount":1,"description":"这是证书描述信息","licenseCheckModel":{"ipAddress":["192.168.245.1","10.0.5.22"],"macAddress":["00-50-56-C0-00-01","50-7B-9D-F9-18-41"],"cpuSerial":"BFEBFBFF000406E3","mainBoardSerial":"L1HF65E00X9"}}
     * @return java.util.Map<java.lang.String                               ,                                                               java.lang.Object>
     * @author小策一喋
     * @date 2018/4/26 13:13
     * @since 1.0.0
     */
    /*
    {
        "subject": "ewsdSC",
            "privateAlias": "privateKey",
            "keyPass": "ewsd04500329",
            "storePass": "ewsd19851013",
            "licensePath": "C:/ewsdSC-license/license.lic",
            "privateKeysStorePath": "C:/ewsdSC-license/server/privateKeys.keystore",
            "issuedTime": "2018-08-18 18:08:18",
            "expiryTime": "2019-08-18 18:08:18",
            "consumerType": "User",
            "consumerAmount": 1,
            "description": "EMIS快速开发平台微服务版",
            "licenseCheckModel": {"ipAddress":["192.168.0.101"],"macAddress":["4C-ED-FB-74-3B-04"],"cpuSerial":"BFEBFBFF000906EA","mainBoardSerial":"180324017510597"}
    }
    */
    @RequestMapping(value = "/generateLicense", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Map<String, Object> generateLicense(@RequestBody(required = true) LicenseCreatorParam param) {
        Map<String, Object> resultMap = new HashMap<>(2);

        if (StringUtils.isBlank(param.getLicensePath())) {
            param.setLicensePath(licensePath);
        }

        //小策一喋
        param.setSubject("zysdEMIS");
        param.setPrivateAlias("privateKey");
        param.setKeyPass("ewsd04500329");
        param.setStorePass("ewsd19851013");

        String licensePath;
        //操作系统类型
        String osName = System.getProperty("os.name").toLowerCase();
        String uuid = Utils.UUIDGenerator();
        if (osName.startsWith("windows")) {
            licensePath = "D:/zysd/cert/emis/" + uuid;
            File fileDir = new File(licensePath);
            fileDir.mkdirs();
            param.setLicensePath(licensePath + "/license.lic");
            param.setPrivateKeysStorePath("D:/license/server/privateKeys.keystore");
        } else {//其他服务器类型
            licensePath = "/home/zysd/cert/emis/" + uuid;
            File fileDir = new File(licensePath);
            fileDir.mkdirs();
            param.setLicensePath(licensePath + "/license.lic");
            param.setPrivateKeysStorePath("/home/license/server/privateKeys.keystore");
        }

        param.setIssuedTime(new Date());
        if (!param.getConsumerType().equals("prod")) {
            param.setExpiryTime(Utils.addDay(30, new Date()));
            param.setConsumerType("dev");
        }

        param.setConsumerAmount(1);
        param.setDescription("EMIS快速开发平台微服务版");
        //小策一碟

        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();

        if (result) {
            resultMap.put("result", "证书文件生成成功！");
            //resultMap.put("msg", param);
        } else {
            resultMap.put("result", "error");
            resultMap.put("msg", "证书文件生成失败！");
        }

        return resultMap;
    }

    @RequestMapping(value = "/generateLicense2")
    @ResponseBody
    public Map<String, Object> generateLicense2(HttpServletRequest request, HttpServletResponse response,
                                                @RequestBody(required = true) LicenseCreatorParam param) {
        Map<String, Object> resultMap = new HashMap<>(2);

        //小策一喋
        param.setSubject("zysdEMIS");
        param.setPrivateAlias("privateKey");
        param.setKeyPass("ewsd04500329");
        param.setStorePass("ewsd19851013");

        String licensePath;
        //操作系统类型
        String osName = System.getProperty("os.name").toLowerCase();
        String uuid = Utils.UUIDGenerator();
        if (osName.startsWith("windows")) {
            licensePath = "D:/zysd/cert/emis/" + uuid;
            File fileDir = new File(licensePath);
            fileDir.mkdirs();
            param.setLicensePath(licensePath + "/license.lic");
            param.setPrivateKeysStorePath("D:/license/server/privateKeys.keystore");
        } else {//其他服务器类型
            licensePath = "/home/zysd/cert/emis/" + uuid;
            File fileDir = new File(licensePath);
            fileDir.mkdirs();
            param.setLicensePath(licensePath + "/license.lic");
            param.setPrivateKeysStorePath("/home/license/server/privateKeys.keystore");
        }

        param.setIssuedTime(new Date());
        if (!param.getConsumerType().equals("prod")) {
            param.setExpiryTime(Utils.addDay(30, new Date()));
            param.setConsumerType("User");
        } else {
            param.setConsumerType("User");
        }

        param.setConsumerAmount(1);
        param.setDescription("EMIS快速开发平台微服务版");
        param.setLicenseCheckModel(param.getLicenseCheckModel());
        //小策一碟

        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();

        if (result) {
            resultMap.put("statusCode", 200);
            resultMap.put("title", "证书文件生成成功！");
            resultMap.put("url", "/license/downloadLicense?uuid=" + uuid);
        } else {
            resultMap.put("statusCode", 300);
            resultMap.put("title", "证书文件生成失败！");
        }
        return resultMap;
    }

    @RequestMapping(value = "/downloadLicense")
    public void downloadLicense(HttpServletRequest request, HttpServletResponse response, String uuid) {

        //操作系统类型
        String osName = System.getProperty("os.name").toLowerCase();
        String fileUrl;
        if (osName.startsWith("windows")) {
            fileUrl = "D:/zysd/cert/emis/" + uuid + "/license.lic";
        } else {//其他服务器类型
            fileUrl = "/home/zysd/cert/emis/" + uuid + "/license.lic";
        }
        String fileName = "license.lic";
        download(request, response, fileUrl, fileName);
    }

    public void download(HttpServletRequest request, HttpServletResponse response, String fileUrl, String fileName) {
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        try {
            // 客户使用保存文件的对话框：
            //fileName = WebUtils.encodeFileName(request, fileName).replaceAll("\\+", "%20");
            fileUrl = new String(fileUrl.getBytes("utf-8"), "utf-8");
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            // 通知客户文件的MIME类型：
            bis = new java.io.BufferedInputStream(new java.io.FileInputStream((fileUrl)));
            bos = new java.io.BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            int i = 0;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                i++;
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                bis = null;
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                bos = null;
            }
        }

    }

}
